package com.zealfi.zxb.api.service;

import com.zealfi.zxb.api.common.Result;
import com.zealfi.zxb.api.mapper.CustMapper;
import com.zealfi.zxb.api.pojo.Cust;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.annotation.EnableCaching;
import org.springframework.context.annotation.Configuration;
import org.springframework.stereotype.Service;
import tk.mybatis.mapper.entity.Example;

import static com.zealfi.zxb.api.common.Status.MOBILE_ALREADY_EXIST;
import static com.zealfi.zxb.api.common.Status.OK;

/**
 * Created by kuan at 2017-10-16 下午 3:59
 */
@Service
@Configuration
@EnableCaching
public class ThirdPartyServiceImpl implements ThirdPartyService {
    private static final Logger logger = Logger.getLogger(ThirdPartyServiceImpl.class);

    @Autowired
    private CustMapper custMapper;

    @Override
    public Result checkMobile(Cust cust) {
        Result result;

        // 判断手机号是否存在
        Cust temp = new Cust();
        temp = custMapper.selectOne(temp);
        if (temp != null) {
            result = new Result(MOBILE_ALREADY_EXIST);
        } else {
            result = new Result(OK);
        }

        return result;
    }

    @Override
    public int register(Cust cust) {
        return custMapper.insertSelective(cust);
    }

    @Override
    public int login(Cust cust) {
        Cust temp = new Cust();
        temp.setTelNo(cust.getTelNo());
        temp = custMapper.selectOne(temp);
        if (temp != null) {
            String pwd = temp.getPwd();
            if (StringUtils.isNotEmpty(pwd) && pwd.equals(cust.getPwd())) {
                cust.setId(temp.getId());
                return 1;
            }
        }

        return 0;
    }

    @Override
    public int changePassword(Cust cust) {
        if (StringUtils.isEmpty(cust.getPwd())) {
            return 0;
        }

        Cust temp = new Cust();
        temp.setPwd(cust.getPwd());
        if (cust.getId() != null) {
            temp.setId(cust.getId());
            return custMapper.updateByPrimaryKeySelective(temp);
        }
        temp.setTelNo(cust.getTelNo());

        Example example = new Example(Cust.class);
        example.createCriteria().andEqualTo("telNo", cust.getTelNo());
        return custMapper.updateByExampleSelective(temp, example);
    }
}
